import { DialogService } from 'ng-devui';
import { PurchaseService } from './../../../@core/services/purchase/purchase.service';
import { SalesService } from './../../../@core/services/sales/sales.service';
import { MessgaeService } from './../../../@core/services/message/messgae.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { environment } from 'src/environments/environment';
import { ReviewDocComponent } from './review-doc/review-doc.component';
import { max } from 'rxjs';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';

@Component({
  selector: 'app-user-center',
  templateUrl: './user-center.component.html',
  styleUrls: ['./user-center.component.scss'],
})
export class UserCenterComponent {
  employeeCode = '';
  employData: any = [];
  headerURL: any = '';
  tabActiveId: string | number = '未读消息';
  noReadMessage = [];
  allMessage = [];
  pager = {
    pageIndex: 1,
    pageSize: 20,
    total: 0,
  };
  pageSizeOptions = [10, 20, 30, 50, 100];
  config = {
    id: 'custom',
    width: '90vw',
    maxHeight: '90vh',
    backdropCloseable: true,
  }; //弹窗配置
  tabActiveTitle = ['未读消息', '全部消息'];
  constructor(
    private UserService: UserService,
    private route: ActivatedRoute,
    private MessgaeService: MessgaeService,
    private SalesService: SalesService,
    private PurchaseService: PurchaseService,
    private DialogService: DialogService,
    private ReviewRolesService: ReviewRolesService
  ) {}
  ngOnInit(): void {
    this.route.params.subscribe((params) => {
      this.tabActiveId = params['type'] || '未读消息';
      this.employeeCode = params['id'];
      this.UserService.GetUserByEmployeeCode(this.employeeCode).subscribe(
        (data: any) => {
          this.employData = data;

          if (this.employData.headImgUrl) {
            this.headerURL =
              environment.modifiedApiUrl + this.employData.headImgUrl;
          }
          this.UserService.GetDepartmentById(data.departmentId).subscribe(
            (res: any) => {
              this.employData.departName = res.name;
            }
          );
          this.MessgaeService.GetPagedMessage({
            pageNumber: this.pager.pageIndex,
            pageSize: this.pager.pageSize,
            readStatus: '未读',
            recipientId: data.id,
          }).subscribe((res: any) => {
            this.noReadMessage = res.items;
            this.pager.total = res.totalCount;
            this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
          });
          this.MessgaeService.GetPagedMessage({
            pageNumber: this.pager.pageIndex,
            pageSize: this.pager.pageSize,
            recipientId: this.employData.id,
          }).subscribe((res: any) => {
            this.allMessage = res.items;
            this.pager.total = res.totalCount;
            this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
          });
        }
      );
    });
  }
  pageIndexChange($event: any) {
    if (this.tabActiveId === '未读消息') {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        readStatus: '未读',
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.noReadMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
      });
    } else if (this.tabActiveId === '全部消息') {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.allMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
      });
    }
  }
  pageSizeChange($event: any) {
    this.pager.pageIndex = 1;
    if (this.tabActiveId === '未读消息') {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        readStatus: '未读',
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.noReadMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
      });
    } else if (this.tabActiveId === '全部消息') {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.allMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
      });
    }
  }
  activeTabChange($event: any) {
    this.pager.pageIndex = 1;
    this.pager.pageSize = 20;
    if ($event === '未读消息') {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        readStatus: '未读',
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.noReadMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
      });
    } else if ($event === '全部消息') {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.allMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
      });
    }
  }
  readMessage(id: any, item?: any) {
    this.MessgaeService.SetMessageAsRead({
      messageId: id,
      userId: this.employData.id,
    }).subscribe((res: any) => {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        readStatus: '未读',
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.noReadMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
      })
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.allMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
      })
    })
  }
  splitMessageContent(content: string): {
    before: string;
    orderNumber: string;
    after: string;
    type: string;
  } {
    const orderNumberPattern =
      /单号:([A-Z0-9-]*\d)(等待审核中|已由其他人员审核通过|您有一条新的单据待审核|审核不通过)?/;
    const match = content.match(orderNumberPattern);
    let type = this.setType(content);
    if (match) {
      const [fullMatch, orderNumber, after] = match;
      const before = content.split(fullMatch)[0];
      return { before, orderNumber, after: after ? after : '', type };
    }
    return { before: content, orderNumber: '', after: '', type };
  }
  generateLink(type: string): string {
    const routeMap: { [key: string]: string } = {
      采购订单审核: '/pages/purchase/purchase-order',
      采购需求单审核: '/pages/purchase/purchase-require',
      采购到货单审核: '/pages/purchase/purchase-arrival',
      采购退货单审核: '/pages/purchase/purchase-return',
      采购委外单审核: '/pages/purchase/purchase-outsource',
      委外到货单审核: '/pages/purchase/purchase-outsource-arrival',
      委外退货单审核: '/pages/purchase/purchase-outsource-return',
      销售报价单审核: '/pages/sales-master/sales-quotation-order',
      销售订单审核: '/pages/sales-master/sales-order',
      销售发货单审核: '/pages/sales-master/sales-Invoice',
      销售退货单审核: '/pages/sales-master/sales-return-order',
    };
    return routeMap[type] || '';
  }
  setType(content: string): string {
    const typeMap: { [key: string]: string } = {
      采购订单: '采购订单审核',
      采购需求单: '采购需求单审核',
      采购到货单: '采购到货单审核',
      采购退货单: '采购退货单审核',
      采购委外单: '采购委外单审核',
      委外到货单: '委外到货单审核',
      委外退货单: '委外退货单审核',
      销售报价单: '销售报价单审核',
      销售订单: '销售订单审核',
      销售发货单: '销售发货单审核',
      销售退货单: '销售退货单审核',
    };
    for (const key in typeMap) {
      if (content.includes(key)) {
        return typeMap[key];
      }
    }
    return '审核类型';
  }
  msgs: { severity: any; summary: any; content: any; }[]

  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  clickCode(code: string, type: string, status: string, dialogtype?: string) {
    let data = {
      code: code,
      type: type,
      disPlay: false,
    };
    const results = this.DialogService.open({
      id: 'custom',
      width: '90vw',
      maxHeight: '90vh',
      backdropCloseable: true,
      content: ReviewDocComponent,
      dialogtype: dialogtype,
      data:data,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '通过',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
            this.ReviewRolesService.ApproveNode(
              results.modalContentInstance.approvalNodeId,
              code
            ).subscribe((res: any) => {
              results.modalInstance.hide();
              this.showToast('success', '成功', '审批成功');
              if (this.tabActiveId === '未读消息') {
                this.MessgaeService.GetPagedMessage({
                  pageNumber: this.pager.pageIndex,
                  pageSize: this.pager.pageSize,
                  readStatus: '未读',
                  recipientId: this.employData.id,
                }).subscribe((res: any) => {
                  this.noReadMessage = res.items;
                  this.pager.total = res.totalCount;
                  this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
                });
              } else if (this.tabActiveId === '全部消息') {
                this.MessgaeService.GetPagedMessage({
                  pageNumber: this.pager.pageIndex,
                  pageSize: this.pager.pageSize,
                  recipientId: this.employData.id,
                }).subscribe((res: any) => {
                  this.allMessage = res.items;
                  this.pager.total = res.totalCount;
                  this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
                });
              }
            },error=>{
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
            }
          );
          }
          else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          cssClass: 'danger',
          text: '驳回',
          handler: ($event: Event) => {
            if(results.modalContentInstance.approvalNodeId){
              console.log()
            if(results.modalContentInstance.reason){
              this.ReviewRolesService.RejectNode(
                results.modalContentInstance.approvalNodeId,
                code,
                results.modalContentInstance.reason
              ).subscribe(
                (res) => {
                  this.showToast('success', '成功', '审批成功');
                  if (this.tabActiveId === '未读消息') {
                    this.MessgaeService.GetPagedMessage({
                      pageNumber: this.pager.pageIndex,
                      pageSize: this.pager.pageSize,
                      readStatus: '未读',
                      recipientId: this.employData.id,
                    }).subscribe((res: any) => {
                      this.noReadMessage = res.items;
                      this.pager.total = res.totalCount;
                      this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
                    });
                  } else if (this.tabActiveId === '全部消息') {
                    this.MessgaeService.GetPagedMessage({
                      pageNumber: this.pager.pageIndex,
                      pageSize: this.pager.pageSize,
                      recipientId: this.employData.id,
                    }).subscribe((res: any) => {
                      this.allMessage = res.items;
                      this.pager.total = res.totalCount;
                      this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
                    });
                  }
                  results.modalInstance.hide();
                },
                (error: any) => {
                  this.showToast(
                    'error',
                    '错误',
                    error.error || '网络连接错误'
                  );
                }
              );
            }else{
              data.disPlay = true
              this.showToast('warn', '警告', '请填写驳回原因');
            }
          }else{
            this.showToast('error', '错误', '没有需要审批的节点');
          }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  allRead() {
    this.MessgaeService.GetPagedMessage({
      pageNumber: this.pager.pageIndex,
      pageSize: this.pager.pageSize,
      recipientId: this.employData.id,
    }).subscribe((res: any) => {
      const data = res.items.map((item) => item.messageId);
      this.MessgaeService.SetBatchMessageAsRead({
        userId: this.employData.id
      },data
    ).subscribe((res: any) => {
        this.MessgaeService.GetPagedMessage({
          pageNumber: this.pager.pageIndex,
          pageSize: this.pager.pageSize,
          readStatus: '未读',
          recipientId: this.employData.id,
        }).subscribe((res: any) => {
          this.noReadMessage = res.items;
          this.pager.total = res.totalCount;
          this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
        });
      });
    });

  }
  allClean() {
    this.MessgaeService.GetPagedMessage({
      pageNumber: this.pager.pageIndex,
      pageSize: this.pager.pageSize,
      recipientId: this.employData.id,
    }).subscribe((res: any) => {
      const data = res.items.map((item) => item.messageId);
      this.MessgaeService.DeleteBatchMessage({
        userId: this.employData.id
      },data
    ).subscribe((res: any) => {
        this.MessgaeService.GetPagedMessage({
          pageNumber: this.pager.pageIndex,
          pageSize: this.pager.pageSize,
          recipientId: this.employData.id,
        }).subscribe((res: any) => {
          this.allMessage = res.items;
          this.pager.total = res.totalCount;
          this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
        });
      });
    });
  }
  delete(){
    this.MessgaeService.DeleteBatchMessage({
      userId: this.employData.id
    },[this.employData.id]
  ).subscribe((res: any) => {
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.allMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[1] = `全部消息(${res.totalCount})`;
      });
      this.MessgaeService.GetPagedMessage({
        pageNumber: this.pager.pageIndex,
        pageSize: this.pager.pageSize,
        readStatus: '未读',
        recipientId: this.employData.id,
      }).subscribe((res: any) => {
        this.noReadMessage = res.items;
        this.pager.total = res.totalCount;
        this.tabActiveTitle[0] = `未读消息(${res.totalCount})`;
      });
    });
  }
}
